package com.itheima.health.security;


import com.itheima.health.pojo.Permission;
import com.itheima.health.service.UserService;
import com.itheima.health.vo.RoleVO;
import com.itheima.health.vo.UserVO;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @author 十一
 * @Description
 * @create 2020-11-13-19:41
 */
@Component
public class HealthUserDetailServiceImpl implements UserDetailsService {
    @Reference
    private UserService userService ;

    /**
     * 根据用户账号查询当前用户的密码，角色信息以及所有权限
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //查询当前用户的基本信息
        UserVO userVO = userService.findUserDetailByUsername(username);
        //判断用户是否为空
        if(userVO == null){
            return null;
        }
        List<GrantedAuthority> grantedAuthorityList = new ArrayList<>();
        Set<RoleVO> roles = userVO.getRoles();
        for (RoleVO role : roles) {
            grantedAuthorityList.add(new SimpleGrantedAuthority(role.getKeyword()));
            Set<Permission> permissionSet = role.getPermissionSet();
            for (Permission permission : permissionSet) {
                grantedAuthorityList.add(new SimpleGrantedAuthority(permission.getKeyword()));
            }
        }
        return new User(username, userVO.getPassword(), grantedAuthorityList);
    }
}
